package cn.fastpay.management.service.impl;

import cn.fastpay.management.entity.PermissionAction;
import cn.fastpay.management.entity.PermissionOperator;
import cn.fastpay.management.entity.PermissionRole;
import cn.fastpay.management.repository.PermissionOperatorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;


/**
 * @author freewolf
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private PermissionOperatorRepository permissionOperatorRepository;

    @Transactional
    @Override
    public UserDetails loadUserByUsername(String var1) throws UsernameNotFoundException {
        // 获取用户
        PermissionOperator operator = permissionOperatorRepository.getByLoginName(var1);
        // 判断空
        if (null == operator) {
            throw new UsernameNotFoundException(var1);
        }
        // 添加权限
        List<GrantedAuthority> grantList = new ArrayList<>();
        // 遍历 Role
        for (PermissionRole role : operator.getRoleSet()) {
            grantList.add(new SimpleGrantedAuthority(role.getRole()));
            // 遍历 Action
            for (PermissionAction action : role.getActionSet()) {
                grantList.add(new SimpleGrantedAuthority(action.getPermission()));
            }
        }
        // 返回一个可以处理 UserDetails 实现
        return new User(operator.getLoginName(), operator.getLoginPassword(),
                true, true, true, operator.getAccountNonLocked(),
                grantList);
    }

}
